package com.mju.config;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.mju.exception.ServiceException;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class KaptchaFilter extends OncePerRequestFilter {	
	@Value("${custom.kaptchaRedisKey}")
	private String kaptchaRedisKey;	
	@Autowired
	private AuthenticationFailureHandler failureHandler;	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Override
	protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain filterChain)
			throws ServletException, IOException {		
		String uri=req.getRequestURI();
		if(uri.equals("/login")&&(req.getMethod().equals("POST"))) {					
			try {
				checkCode(req);
				log.error("验证通过....");
			}
			catch(ServiceException ex) {
				log.error("验证未通过....");
				failureHandler.onAuthenticationFailure(req, resp, ex);
				return;
			}			
		}			
		filterChain.doFilter(req, resp);
	}
	
	private void checkCode(HttpServletRequest req) throws ServiceException
	{
		String code=req.getParameter("verifyCode");
		String uuid=req.getParameter("uuid");
		if(!StringUtils.hasText(code)||!StringUtils.hasText(uuid))
			throw new ServiceException(463,"请输入验证码");
			
		String redisValue=redisTemplate.opsForValue().get(kaptchaRedisKey+uuid);
		
		if(!StringUtils.hasText(redisValue))
			throw new ServiceException(464,"验证码已过期");
		
		if(!redisValue.equalsIgnoreCase(code))
			throw new ServiceException(465,"验证码不匹配");
			
		redisTemplate.delete(kaptchaRedisKey+uuid);	
	}
}
